﻿package com.bike.util;

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailSender {
	private static final String charset = "utf-8";
	private static final String defaultMimetype = "text/plain";

	public static void main(String[] args) throws Exception {
		boolean ss = EmailSender.send(new String[] { "weizhenghai@icaipiao123.com" },
				"sessdddion",
				"ddddd",
				null, null);
		System.out.println("ss:" + ss);

	}

	/**
	 * 发送邮件
	 * 
	 * @param receiver
	 *            收件人
	 * @param subject
	 *            标题
	 * @param mailContent
	 *            邮件内容
	 * @param mimetype
	 *            内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
	 */
	public static void send(String receiver, String subject,
			String mailContent, String mimetype) {
		send(new String[] { receiver }, subject, mailContent, mimetype);
	}

	/**
	 * 发送邮件
	 * 
	 * @param receivers
	 *            收件人
	 * @param subject
	 *            标题
	 * @param mailContent
	 *            邮件内容
	 * @param mimetype
	 *            内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
	 */
	public static void send(String[] receivers, String subject,
			String mailContent, String mimetype) {
		send(receivers, subject, mailContent, null, mimetype);
	}

	/**
	 * 发送邮件
	 * 
	 * @param receivers
	 *            收件人
	 * @param subject
	 *            标题
	 * @param mailContent
	 *            邮件内容
	 * @param attachements
	 *            附件
	 * @param mimetype
	 *            内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
	 */
	public static boolean send(String[] receivers, String subject,
			String mailContent, File[] attachements, String mimetype) {
		Properties props = new Properties();
		 
	    // 开启debug调试
	    props.setProperty("mail.debug", "true");
	    // 发送服务器需要身份验证
	    props.setProperty("mail.smtp.auth", "true");
	    // 设置邮件服务器主机名
	    props.setProperty("mail.host", "smtp.exmail.qq.com");
	    // 发送邮件协议名称
	    props.setProperty("mail.transport.protocol", "smtp");
	 
	    MailSSLSocketFactory sf;
		try {
			sf = new MailSSLSocketFactory();
		    sf.setTrustAllHosts(true);
		    props.put("mail.smtp.ssl.enable", "true");
		    props.put("mail.smtp.ssl.socketFactory", sf);
		} catch (GeneralSecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				
				return new PasswordAuthentication("duobaokefu@icaipiao123.com",
						"Welcome2duobao");// 登录用户名/密码
			}
		});
		 session.setDebug(true);
		try {
			MimeMessage mimeMessage = new MimeMessage(session);
			mimeMessage.setFrom(new InternetAddress("duobaokefu@icaipiao123.com",
					"夺宝奇兵"));// 发件人邮件

			InternetAddress[] toAddress = new InternetAddress[receivers.length];
			for (int i = 0; i < receivers.length; i++) {
				toAddress[i] = new InternetAddress(receivers[i]);
			}
			mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);// 收件人邮件
			mimeMessage.setSubject(subject, charset);

			Multipart multipart = new MimeMultipart();
			// 正文
			MimeBodyPart body = new MimeBodyPart();
			// body.setText(message, charset);不支持html
			body.setContent(mailContent,
					(mimetype != null && !"".equals(mimetype) ? mimetype
							: defaultMimetype) + ";charset=" + charset);
			multipart.addBodyPart(body);// 发件内容
			// 附件
			if (attachements != null) {
				for (File attachement : attachements) {
					MimeBodyPart attache = new MimeBodyPart();
					// ByteArrayDataSource bads = new
					// ByteArrayDataSource(byte[],"application/x-any");
					attache.setDataHandler(new DataHandler(new FileDataSource(
							attachement)));
					String fileName = getLastName(attachement.getName());
					attache.setFileName(MimeUtility.encodeText(fileName,
							charset, null));
					multipart.addBodyPart(attache);
				}
			}
			mimeMessage.setContent(multipart);
			// SimpleDateFormat formcat = new SimpleDateFormat("yyyy-MM-dd");
			mimeMessage.setSentDate(new Date());// formcat.parse("2010-5-23")
			Transport.send(mimeMessage);

		} catch (Exception e) {
			e.printStackTrace();
			// System.out.println("sendemail" + e.getMessage());
			System.out.println("邮箱发送失败");
			return false;

		}
		return true;
	}

	private static String getLastName(String fileName) {
		int pos = fileName.lastIndexOf("\\");
		if (pos > -1) {
			fileName = fileName.substring(pos + 1);
		}
		pos = fileName.lastIndexOf("/");
		if (pos > -1) {
			fileName = fileName.substring(pos + 1);
		}
		return fileName;
	}
}
